//
//  main.m
//  homework4
//
//  Created by dllo on 16/7/8.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Color.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *path = @"/Users/dllo/DLS160710/Objective-C/HomeWork/homework4/homework4/crayons.txt";
        // 通过文件路径读取文件中的字符串
        NSString *sourceStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        NSLog(@"%@",sourceStr);
        // 根据\n切割字符串
        NSArray *colorStringArray = [sourceStr componentsSeparatedByString:@"\n"];
        // 声明储存颜色的可变字典
        NSMutableDictionary *colorDictionary = [NSMutableDictionary dictionary];
        for (int i = 0; i < colorStringArray.count; i++) {
            // 去除空格
            if ([colorStringArray[i] length] > 0) {
                NSLog(@"%@",colorStringArray[i]);
                NSArray *color = [colorStringArray[i] componentsSeparatedByString:@" #"];
                [colorDictionary setObject:[color lastObject] forKey:[color firstObject]];
            }
        }
        
        NSLog(@"%@",colorDictionary);
        // 2.
        NSMutableDictionary *newColorDictionary = [NSMutableDictionary dictionary];
        NSArray *allkeys = colorDictionary.allKeys;
        
        for (int i = 0;i < allkeys.count; i++) {
            NSString *subString = [allkeys[i] substringWithRange:NSMakeRange(0, 1)];
            NSMutableArray *colorArray = [newColorDictionary objectForKey:subString];
            Color *newColor = [[Color alloc] init];
            newColor.colorName = allkeys[i];
            newColor.colorValue = [colorDictionary objectForKey:allkeys[i]];
            // 判断从新字典中的数组是否为空
            // 为空说明,对应的是字母的数组没有
            if (colorArray == nil) {
                // 创建
                colorArray = [NSMutableArray arrayWithObject:newColor];
                // 赋值给对应的首字母
                [newColorDictionary setObject:colorArray forKey:subString];
            } else {
                // 说明之前已经存过,直接添加
                [colorArray addObject:newColor];
            }
            
        }
        NSLog(@"%@",newColorDictionary);
    }
    return 0;
}
